<template>
  <div class="app-container">
    <el-form
      v-show="showSearch"
      ref="queryFormRef"
      :model="queryParams"
      :inline="true"
      label-width="68px"
    >
      <el-form-item
        :label="$t('system.myMsg.title')"
        prop="title"
      >
        <el-input
          v-model="queryParams.title"
          :placeholder="$t('system.myMsg.enterTitle')"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="ele-Search"
          @click="handleQuery"
        >
          {{ $t("system.myMsg.search") }}
        </el-button>
        <el-button
          icon="ele-Refresh"
          @click="resetQuery"
        >
          {{ $t("system.myMsg.reset") }}
        </el-button>
      </el-form-item>
    </el-form>

    <el-row
      :gutter="10"
      class="mb8"
    >
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="ele-View"
          @click="handleAllRead"
        >
          {{ $t("system.myMsg.markAllRead") }}
        </el-button>
      </el-col>
      <right-toolbar
        v-model:show-search="showSearch"
        @query-table="getList"
      />
    </el-row>

    <el-table
      v-loading="loading"
      :data="announcementList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
      />
      <el-table-column
        label="ID"
        align="center"
        prop="id"
      />
      <el-table-column
        :label="$t('system.myMsg.title')"
        width="400"
        align="center"
        prop="title"
        show-overflow-tooltip
      />
      <el-table-column
        :label="$t('system.myMsg.publisher')"
        align="center"
        prop="sender"
      />
      <el-table-column
        :label="$t('system.myMsg.priority')"
        align="center"
        prop="priorityDesc"
      />
      <el-table-column
        :label="$t('system.myMsg.messageType')"
        align="center"
        prop="msgCategoryDesc"
      />
      <el-table-column
        :label="$t('system.myMsg.publishTime')"
        align="center"
        prop="sendTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.sendTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('system.myMsg.readStatus')"
        align="center"
        prop="readFlag"
      >
        <template #default="scope">
          <el-tag
            v-if="scope.row.readFlag"
            type="success"
          >
            {{ $t("system.myMsg.read") }}
          </el-tag>
          <el-tag
            v-else
            type="danger"
          >
            {{ $t("system.myMsg.unread") }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('system.myMsg.operation')"
        align="center"
        class-name="small-padding fixed-width"
        width="200"
      >
        <template #default="scope">
          <el-tooltip
            :content="$t('system.myMsg.view')"
            placement="top"
          >
            <el-button
              link
              type="primary"
              icon="ele-View"
              @click="handleView(scope.row)"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.current"
      v-model:limit="queryParams.size"
      @pagination="getList"
    />

    <el-dialog
      v-if="showOpen"
      :title="$t('system.myMsg.notificationDetails')"
      v-model="showOpen"
      width="800px"
      append-to-body
    >
      <iframe
        :src="showDetailUrl"
        class="detail-iframe"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showOpen = false">{{ $t("formI18n.all.cancel") }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onBeforeMount, onMounted, ref } from "vue";
import { useRoute } from "vue-router";
import { getMyAnnouncementSend, Message, readAllAnnouncementSend, readAnnouncementSend } from "@/api/system/announcement";
import { addBaseUrl, getTokenUrl } from "@/utils/auth";
import mittBus from "@/utils/mitt";
import { i18n } from "@/i18n";
import { parseTime } from "@/utils/tduck";
import { ElMessageBox, FormInstance } from "element-plus";

interface QueryParams {
  current: number;
  size: number;
  delFlag: boolean;
  title: string | null;
}

// 状态定义
const loading = ref(true);
const ids = ref<number[]>([]);
const single = ref(true);
const multiple = ref(true);
const showSearch = ref(true);
const total = ref(0);
const announcementList = ref<Message[]>([]);
const showOpen = ref(false);
const showDetailUrl = ref("");
const queryFormRef = ref<FormInstance>();

const queryParams = ref<QueryParams>({
  current: 1,
  size: 10,
  delFlag: false,
  title: null
});

// 方法定义
const getList = async () => {
  loading.value = true;
  try {
    const response = await getMyAnnouncementSend(queryParams.value);
    announcementList.value = response.data.records;
    total.value = response.data.total;
  } finally {
    loading.value = false;
  }
};

const handleQuery = () => {
  queryParams.value.current = 1;
  getList();
};

const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

const handleSelectionChange = (selection: Message[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

const handleView = async (row: Message) => {
  if (!row.readFlag && row.anntId) {
    await readAnnouncementSend(row.anntId as number);
  }

  row.readFlag = true;
  if (row.openType && row.openType === "url") {
    window.open(addBaseUrl(row.openPage || "") + "&msgOpen=true", "_blank");
  } else {
    showOpen.value = true;
    showDetailUrl.value = getTokenUrl("/sys/announce/show/" + row.anntId);
  }
};

const handleAllRead = () => {
  ElMessageBox.confirm(i18n.global.t("system.myMsg.confirmMarkAllRead"), i18n.global.t("formI18n.all.waring"), {
    confirmButtonText: i18n.global.t("formI18n.all.confirm"),
    cancelButtonText: i18n.global.t("formI18n.all.cancel"),
    type: "warning"
  })
    .then(async () => {
      await readAllAnnouncementSend();
      // 抛出事件 红点消失
      mittBus.emit("sysMsgNotice", {});
      await getList();
    })
    .catch(() => {});
};
// 如果携带参数到这个页面 直接打开消息
const route = useRoute();
onBeforeMount(() => {
  if (route.query.msgId) {
    // 给工作台使用
    handleView({
      msgContent: "",
      anntId: Number(route.query.msgId)
    });
  }
});

// 生命周期
onMounted(() => {
  getList();
});

defineEmits<{
  (e: "sysMsgNotice"): void;
}>();
</script>

<style>
.detail-iframe {
  border: 0;
  width: 100%;
  min-height: 600px;
}
</style>
